<template>
  <!-- 编辑头像组件 -->
  <div class="update-avatar">
    <img :src="imgUrl" alt="" ref="img">
    <div class="toolbar">
      <span @click="$emit('closePopup')">取消</span>
      <span @click="onComfirm">完成</span>
    </div>
  </div>
</template>

<script>
// 导入裁剪依赖
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
// 导入修改头像请求
import { setUserAvatar } from '@/api/user.js'
export default {
  data () {
    return {}
  },
  props: {
    imgUrl: {
      type: String,
      require: true
    }
  },
  methods: {
    // 完成
    onComfirm () {
      this.$toast.loading({
        message: '修改中...',
        forbidClick: true,
        duration: 0
      })
      // 服务器裁剪
      // 获取裁剪信息 this.cropper.getData()
      // 客户端裁剪
      // 把裁剪区域画到画布上 获取canvas画布(裁剪区域) this.cropper.getCroppedCanvas()
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        // 二进制数据blob
        // 创建表单数据
        const formData = new FormData()
        // 添加key为photo的表单数据
        formData.append('photo', blob)
        try {
          const { data: res } = await setUserAvatar(formData)
          this.$toast('修改头像成功')
          // 关闭弹层
          this.$emit('closePopup')
          // 同步视图
          this.$emit('updataSuccess', res.data.photo)
        } catch (err) {
          this.$toast('修改头像失败')
        }
      })
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () { },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false // 关闭默认背景
    })
  }
}
</script>

<style scoped lang='less'>
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
